import React, {useCallback, useEffect, useState} from "react"
import {ConfigProvider, Table} from "antd";
import {getAllMarketsOnlyICanSee} from "../../apis/MarketsApi";
import DataPageLayout from "../../components/DataPageLayout";
import {NumberIdAndName} from "../../types/BasicModels";
import {useNavigate, useSearchParams} from "react-router-dom";
import {Pageable} from "../../utils/Page";
import {
    castFilterValue,
    mergePaginationAndPageable,
    useTableFilterDateRangeColumnProps,
    useTableSearchTextColumnProps
} from "../../utils/AntdTableUtils";
import {LocalDate} from "@js-joda/core";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import {
    MarketDeliveryOrderStatus, marketDeliveryOrderStatuses,
    marketDeliveryOrderStatusMap,
    QueryMarketDeliveryOrderResponse,
    queryMarketDeliveryOrders
} from "../../apis/MarketDeliveryOrderApi";
import {useGlobalStyle} from "../../global.style";
import {QueryMarketOrderResponse} from "../../apis/MarketOrderApi";
import {YEAR_MONTH_DAY_FORMATER} from "../../utils/Date";

export interface pageProps {

}

export interface MarketOrderFormData {
    marketId: number
}


const MarketDeliveryOrderPage: React.FC<pageProps> = (props) => {
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryMarketDeliveryOrderResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    let [urlSearchParams] = useSearchParams();
    const [marketIds, setMarketIds] = useState<number[]>(urlSearchParams.getAll("marketIds").map(it => parseInt(it)))

    const [markets, setMarkets] = useState<Array<NumberIdAndName>>([])
    useEffect(() => {
        getAllMarketsOnlyICanSee().then(response => {
            setMarkets(response.data)
        })
    }, []);


    let searchNumberTableColumnProps = useTableSearchTextColumnProps<QueryMarketDeliveryOrderResponse>("number", {
        placeholder: "编号"
    });
    const [number,setNumber] = useState<string>()
    const [startCreatedDate, setStartCreatedDate] = useState<string>()
    const [endCreatedDate, setEndCreatedDate] = useState<string>()
    const [startValidatedDate,setStartValidatedDate] = useState<string>()
    const [endValidatedDate,setEndValidatedDate] = useState<string>()
    const [status,setStatus] = useState<MarketDeliveryOrderStatus>()

    const query = useCallback(()=>{
        setLoading(true)
        queryMarketDeliveryOrders({
            marketIds,
            startCreatedDate: startCreatedDate ? LocalDate.parse(startCreatedDate).format(YEAR_MONTH_DAY_FORMATER) : undefined,
            endCreatedDate: endCreatedDate ? LocalDate.parse(endCreatedDate).format(YEAR_MONTH_DAY_FORMATER) : undefined,
            validatedStartDate:startValidatedDate,
            validatedEndDate: endValidatedDate,
            status,
            number,
        },pageable).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    },[...pageable.toDependencyList(), marketIds,  startCreatedDate, endCreatedDate,startValidatedDate,endValidatedDate,status,number])
    useEffect(() => {
        query()
    }, [query]);

    let navigate = useNavigate();
    let globalStyle = useGlobalStyle();
    return <>
        <DataPageLayout>
            <ConfigProvider componentSize={"small"}>
                <Table<QueryMarketDeliveryOrderResponse> className={globalStyle.rowClickableTable} onRow={item => {
                    return {
                        onClick: () => {
                            navigate(`/markets/deliveryOrders/${item.id}`)
                        }
                    }
                }} size={"small"} loading={loading} dataSource={data} rowKey={"id"} pagination={{
                    current: pageable.page,
                    pageSize: pageable.size,
                    total: totalElements,
                }} onChange={(pagination, filters, sorter) => {
                    setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                    setMarketIds(filters["market.name"] as number[])
                    setStatus((filters["status"] as MarketDeliveryOrderStatus[])[0])
                    setNumber(castFilterValue(filters.number))
                }}>
                    <Table.Column<QueryMarketDeliveryOrderResponse> key={"number"} title={"编号"} dataIndex={"number"} {...searchNumberTableColumnProps}/>
                    <Table.Column<QueryMarketDeliveryOrderResponse> filteredValue={marketIds}
                                                                    dataIndex={["market", "name"]}
                                                                    key={"marketIds"}
                                                                    title={"卖场"}
                                                                    filters={markets.map(market => {
                                                                        return {
                                                                            text: market.name,
                                                                            value: market.id,
                                                                        }
                                                                    })}
                                                                    render={(_, record) => {
                                                                        return record.market.name
                                                                    }}/>
                    <Table.Column dataIndex={"createdDateTime"} title={"开单时间"}
                                  {...useTableFilterDateRangeColumnProps<QueryMarketDeliveryOrderResponse>("createdDateTime", {
                                      handleSearch:value => {
                                          setStartCreatedDate(value?value[0].format():undefined)
                                          setEndCreatedDate(value?value[1].format():undefined)
                                      }
                                  })}
                                  render={(value) => LocalDate.parse(value).format(YEAR_MONTH_DAY_FORMATER)}/>
                    <Table.Column dataIndex={"createdDateTime"} title={"验货时间"}
                                  {...useTableFilterDateRangeColumnProps<QueryMarketDeliveryOrderResponse>("validatedDateTime", {handleSearch:value => {
                                          setStartValidatedDate(value?value[0].format():undefined)
                                          setEndValidatedDate(value?value[1].format():undefined)
                                      }})}
                                  render={(value) => LocalDate.parse(value).format(YEAR_MONTH_DAY_FORMATER)}/>
                    <Table.Column dataIndex={["goodsKindAmount"]} title={"单品数量"}/>
                    <Table.Column<QueryMarketDeliveryOrderResponse> dataIndex={"status"}
                                                            filteredValue={status?[status]:[]}
                                                            title={"状态"}
                                                            key={"status"}
                                                            filterMultiple={false}
                                                            filters={marketDeliveryOrderStatuses.map(it => ({
                                                                text: marketDeliveryOrderStatusMap[it],
                                                                value: it
                                                            }))} render={(_, record) => {
                        return marketDeliveryOrderStatusMap[record.status]
                    }}/>

                </Table>
            </ConfigProvider>

        </DataPageLayout>
    </>
}
export default observerDashboardPageWrapper(MarketDeliveryOrderPage,"markets/deliveryOrders","卖场送货单")
